package com.fruit.api.controller.fruit;

import com.fruit.api.controller.BaseController;
import com.fruit.bean.dto.fruit.FruitUserOrderInfoDto;
import com.fruit.bean.dto.fruit.FruitUserOrderPayDto;
import com.fruit.bean.dto.fruit.FruitUserOrderPlaceDto;
import com.fruit.bean.entity.fruit.FruitProfitInfo;
import com.fruit.bean.entity.fruit.FruitSellRequestInfo;
import com.fruit.bean.entity.fruit.FruitShelfInfo;
import com.fruit.bean.entity.fruit.FruitUserOrderInfo;
import com.fruit.bean.entity.system.User;
import com.fruit.bean.enumeration.fruit.FruitUserOrderStatusEnum;
import com.fruit.bean.vo.front.Rets;
import com.fruit.service.fruit.*;
import com.fruit.service.system.UserService;
import com.fruit.utils.BigDecimalUtils;
import com.fruit.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fruit/user/order")
public class FruitUserOrderController extends BaseController {

    @Autowired
    private FruitUserOrderService userOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private FruitShelfService shelfService;

    @Autowired
    private FruitShoppingCartService shoppingCartService;

    @Autowired
    private FruitProfitService profitService;

    @Autowired
    private FruitSellRequestService sellRequestService;

    /**
     * 管理端获取所有用户订单列表
     * @return
     */
    @RequestMapping("/list")
    public Object listUserOrder(){
        return Rets.success(userOrderService.queryUserOrderPage());
    }

    /**
     * 小程序端用户获取自己的订单列表
     * @param map userId 用户id
     * @return
     */
    @RequestMapping("/app/list")
    public Object listUserOrder(@RequestBody Map<String,Long> map){
        List<FruitUserOrderInfoDto> userOrderInfoDtoList = userOrderService.listUserOrderInfo(map.get("userId"));
        return Rets.success(userOrderInfoDtoList);
    }

    /**
     * 用户下单 TODO 目前只支持一次下单一种水果。
     * @return
     */
    @RequestMapping("/place")
    public Object userPlaceOrder(@RequestBody FruitUserOrderPlaceDto placeDto){
        FruitUserOrderInfo userOrderInfo = new FruitUserOrderInfo();
        userOrderInfo.setFruitShelfId(placeDto.getShelfId());
        userOrderInfo.setUserOrderNumber(placeDto.getUserOrderNumber());
        userOrderInfo.setUserOrderTime(new Date());
        userOrderInfo.setUserId(placeDto.getUserId());
        userOrderInfo.setUserOrderPrice(placeDto.getUserOrderPrice());
        userOrderInfo.setUserAddressId(placeDto.getUserAddressId());
        //计算用户支付总价
        BigDecimal b = new BigDecimal(placeDto.getUserOrderNumber()*placeDto.getUserOrderPrice());
        Double m_price = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        userOrderInfo.setUserOrderPay(m_price);
        userOrderInfo.setUserOrderStatus(FruitUserOrderStatusEnum.TO_BE_PAY.getCode());
        userOrderInfo = userOrderService.insert(userOrderInfo);
        //返回订单id
        return Rets.success(userOrderInfo.getId());
    }

    /**
     * 用户支付
     * @param payDto 订单id和购物车id
     * @return
     */
    @RequestMapping("/pay")
    public Object userOrderPay(@RequestBody FruitUserOrderPayDto payDto) {
        Long userOrderId = payDto.getUserOrderId();
        Long shoppingCartId = payDto.getShoppingCartId();
        FruitUserOrderInfo userOrderInfo = userOrderService.get(userOrderId);
        // 确认订单是否为待支付支付，不是则返回错误信息
        if (userOrderInfo.getUserOrderStatus() != FruitUserOrderStatusEnum.TO_BE_PAY.getCode()) {
            for (FruitUserOrderStatusEnum orderStatusEnum : FruitUserOrderStatusEnum.values()) {
                if (orderStatusEnum.getCode().equals(userOrderInfo.getUserOrderStatus())) {
                    String orderStatusStr = orderStatusEnum.getMsg();
                    return Rets.failure(orderStatusStr);
                }
            }
        }
        //确认库存是否足够
        FruitShelfInfo shelfInfo = shelfService.get(userOrderInfo.getFruitShelfId());
        if (shelfInfo.getFruitSellNumber() < userOrderInfo.getUserOrderNumber()) {
            return Rets.failure("库存不足");
        }

        Long userId = userOrderInfo.getUserId();
        //用户账户扣款
        User user = userService.get(userId);
        //确认用户余额是否足够
        if (user.getMoney() < userOrderInfo.getUserOrderPay()) {
            return Rets.failure("账户金额不足。请充值后再支付。");
        }
        user.setMoney(user.getMoney() - userOrderInfo.getUserOrderPay());
        userService.update(user);

        //更新订单状态
        userOrderInfo.setUserOrderStatus(FruitUserOrderStatusEnum.PAID.getCode());
        // TODO 更新订单状态出错，需要处理
        userOrderService.updateOrderInfo(userOrderInfo);

        //如果是购物车支付，删除购物车信息
        if (null != shoppingCartId) {
            shoppingCartService.delete(shoppingCartId);
        }

        //更新库存信息
        shelfInfo.setFruitSellNumber(BigDecimalUtils.sub(shelfInfo.getFruitSellNumber(),
                userOrderInfo.getUserOrderNumber()).doubleValue());
        shelfService.update(shelfInfo);

        // 用户支付计算收益
        FruitProfitInfo profitInfo = new FruitProfitInfo();
        FruitSellRequestInfo sellRequestInfo = sellRequestService.get(shelfInfo.getFruitSellRequestId());

        profitInfo.setCreateTime(new Date());
        profitInfo.setProfitType(1);
        profitInfo.setShelfInfoId(shelfInfo.getId());
        double profit = BigDecimalUtils.mul(
                BigDecimalUtils.sub(sellRequestInfo.getFruitLastPrice(),
                        sellRequestInfo.getFruitSellPrice()).doubleValue(),
                userOrderInfo.getUserOrderNumber()).doubleValue();
        if (profit != 0){
            profitInfo.setProfit(profit);
            profitService.insert(profitInfo);
        }

        return Rets.success();
    }

    /**
     * 取消支付(暂不支持取消支付)
     * @param userOrderId 用户订单id
     * @return
     */
    @RequestMapping("/cancel")
    public Object userOrderCancel(Long userOrderId){
        FruitUserOrderInfo userOrderInfo = userOrderService.get(userOrderId);
        //userOrderInfo.setUserOrderStatus(FruitUserOrderStatusEnum.CANCEL.getCode());
        userOrderService.update(userOrderInfo);
        return Rets.success();
    }

    /**
     * 取消支付(暂不支持取消支付)
     * @param map userOrderId 用户订单id
     * @return
     */
    @RequestMapping("/recieve")
    public Object userOrderRecieve(@RequestBody Map<String,Long> map){
        Long userOrderId = map.get("userOrderId");
        FruitUserOrderInfo userOrderInfo = userOrderService.get(userOrderId);
        userOrderInfo.setUserOrderStatus(FruitUserOrderStatusEnum.WAIT_EVALUATE.getCode());
        userOrderService.update(userOrderInfo);
        return Rets.success();
    }

    /**
     * 删除订单
     * @param userOrderId 用户订单id
     * @return
     */
    @RequestMapping("/delete")
    public Object userOrderDelete(Long userOrderId){
        FruitUserOrderInfo userOrderInfo = userOrderService.get(userOrderId);
        userOrderInfo.setUserOrderStatus(FruitUserOrderStatusEnum.DELETED.getCode());
        userOrderService.update(userOrderInfo);
        return Rets.success();
    }

    /**
     * 用户充值
     * @param rechargeAmoungt 充值金额
     * @return
     */
    @RequestMapping("/recharge")
    public Object userRecharge(Float rechargeAmoungt){
        if(rechargeAmoungt <= 0){
            return Rets.failure("请输入正确的金额");
        }
        HttpServletRequest request = HttpUtil.getRequest();
        Long userId = getUserId(request);
        User user = userService.get(userId);
        user.setMoney(user.getMoney()+rechargeAmoungt);
        userService.update(user);
        return Rets.success();
    }

}
